// URLSearhParams is good ,
// but can't handle query value containing "spance" and "+" as expected
// so we use this module to parse query string

function parseQuery(url: string, isDecode = true) {
  const query: Obj = {};
  const queryString = url.includes('?') ? url.replace(/^.*?\?/, '') : url;
  if (!queryString) return query;
  const params = queryString.split('&');
  params.forEach(param => {
    const [key, value] = param.split('=');
    query[key] = isDecode ? decodeURIComponent(value) : value;
  });
  return query;
}

function stringifyQuery(query: Obj, isEncode = true) {
  const params: string[] = [];
  Object.keys(query).forEach(key => {
    const value = query[key];
    params.push(`${key}=${isEncode ? encodeURIComponent(value) : value}`);
  });
  return params.join('&');
}

export { parseQuery, stringifyQuery };
